# -*- coding: utf-8 -*-
import logging
import os
from Qt.QtWidgets import *
import maya.cmds as mc
import maya.mel as mel
from liberLibs.dccLibs import Maya
from liberHook.BaseHook import BaseHook
from liberLibs.utils import read_json
from liberLibs.dccLibs import Xgen


class Hook(BaseHook):
    def __init__(self, library, directory, ext, start, end):
        super(Hook, self).__init__(library, directory, ext, start, end)

    def execute(self):
        # check abc .xgen .xgd is exist
        hair_cache_path = "%s/abc/scalp.abc" % self.directory
        xgen_file_path = str(self.file)
        if not all((os.path.isfile(hair_cache_path),
                    os.path.isfile(xgen_file_path))):
            self.append_error("cache .xgen .xgd file missed.")
            return
        # load plugin
        Maya.load_plugin("xgenToolkit.mll")
        mel.eval("XgCreateDescriptionEditor;")
        # import abc cache
        namespace, ok = QInputDialog.getText(None, "namespace", "Input a namespace", text=":")
        if not all((namespace, ok)):
            return
        namespace = str(namespace)
        mc.file(hair_cache_path, i=1, namespace=namespace, f=1)
        logging.info("Import cache done.")
        # import palette
        x = Xgen.Xgen()
        x.import_palette(xgen_file_path, [], namespace)
        logging.info("Import xgen done.")
        # import shader
        shd_path = "%s/shader/shader.ma" % self.directory
        shd_path = shd_path.replace("\\", "/")
        connection_path = "%s/shader/shader.json" % self.directory
        connection_path = connection_path.replace("\\", "/")
        if os.path.isfile(shd_path):
            mc.file(shd_path, i=1)
            connection_path = connection_path
            if os.path.isfile(connection_path):
                data = read_json(connection_path)
                for description in data:
                    sg = data.get(description)
                    try:
                        if namespace != ":":
                            description = "%s:%s" % (namespace, description)
                        mc.sets(description, fe=sg)
                    except:
                        logging.info("Can't assign shader %s --> %s" % (description, sg))
                logging.info("assign shader done.")
